package ustc.xiaoyang.lingchashan.doublepointer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 18. 四数之和 medium
 */
public class fourSum18 {
    public List<List<Integer>> fourSum(int[] nums,int target){
        List<List<Integer>> res = new ArrayList<>();
        int n = nums.length;
        Arrays.sort(nums);
        for (int i = 0; i < n - 3; i++) {
            if(i>0 && nums[i] == nums[i-1]) continue;
            if(i > target && nums[i] > 0) break;
            for (int j = i+1; j < n - 2; j++) {
                if(j>i+1 && nums[j] == nums[j-1]) continue;
                if(nums[i] + nums[j] > target && nums[i] + nums[j] > 0) break;
                int l = j + 1;
                int r = n - 1;
                while(l<r){
                    int sum = nums[i] + nums[j] + nums[l] + nums[r];
                    if(sum == target){
                        res.add(List.of(nums[i],nums[j],nums[l],nums[r]));
                        l++;
                        r--;
                        while(l<r && nums[l] == nums[l-1]) l++;
                        while(l<r && nums[r] == nums[r+1]) r--;
                    }else if(sum < target){
                        l++;
                    }else{
                        r--;
                    }
                }
            }
        }
        return res;
    }

}
